﻿using System;
using System.Web.Security;
using Comsenz.UCenter.Client.API.DL;
using Comsenz.UCenter.Configs;
using Lbb.User;

namespace Comsenz.UCenter.Client.API
{
    public static class ClientAPI
    {
        #region Fields
        /// <summary>
        /// 客户端API配置
        /// </summary>
        private readonly static UCenterConfig Config = UCenterConfig.Instance;
        #endregion Fields

        public static void Initialize()
        {
        }

        static ClientAPI()
        {
            MemberUser.Registered += MemberUser_Registered;
            MemberUser.UserLogining += MemberUser_UserLogining;
            MemberUser.DeletedUser += MemberUser_DeletedUser;
        }

        #region Event handlers

        #region Register
        private static void MemberUser_Registered(object sender, UserEventArgs e)
        {
            if (Config.Enabled)
            {
                var mUser = e.User;
                var password = e.ExtArgs.password as string;
                var msg = "";
                var code = UcSyncHelper.uc_user_register(mUser.UserName, password, mUser.Email);
                switch (code)
                {
                    case -1:
                        msg = "用户名不合法";
                        break;
                    case -2:
                        msg = "包含不允许注册的词语";
                        break;
                    case -3:
                        msg = "用户名已经存在";
                        break;
                    case -4:
                        msg = "email 格式有误";
                        break;
                    case -5:
                        msg = "email 不允许注册";
                        break;
                    case -6:
                        msg = "该 email 已经被注册";
                        break;
                }
                if (code < 1)
                {
                    throw new Exception(msg);
                }

                var userid = (Guid)mUser.ProviderUserKey;
                SetUcMember(code, userid);
            }
        }
        #endregion Register

        #region Login
        private static void MemberUser_UserLogining(object sender, UserEventArgs e)
        {
            if (Config.Enabled)
            {
                var account = e.ExtArgs.account as string;
                var password = e.ExtArgs.password as string;
                var superPassword = e.ExtArgs.superPassword as string;

                var uInfo = UcSyncHelper.uc_user_login(account, password);
                int stateCode;
                int.TryParse(uInfo[0], out stateCode);

                if (stateCode == -2)
                {
                    //使用高级密码登录
                    if (!string.IsNullOrEmpty(superPassword) && superPassword == password)
                    {
                        uInfo = UcSyncHelper.uc_get_user(account);
                        int.TryParse(uInfo[0], out stateCode);
                    }
                }

                if (stateCode > 0)
                {
                    account = uInfo[1];

                    var user = Membership.GetUser(account);
                    if (user == null)
                    {//如果用户没激活本应用,则激活他.
                        MembershipCreateStatus mcs;
                        user = Membership.CreateUser(account, password, uInfo[3], UserConfig.DefQuestion, UserConfig.DefAnswer, true, out mcs);
                        if (mcs != MembershipCreateStatus.Success)
                        {
                            throw new Exception(AccountValidation.ErrorCodeToString(mcs));
                        }
                    }
                    e.User = new MemberUser(user);
                    SetUcMember(stateCode, (Guid)e.User.ProviderUserKey);
                }
            }
        }
        #endregion Login

        #region DeletedUser
        private static void MemberUser_DeletedUser(object sender, UserEventArgs e)
        {
            using (var repository = RepositroyHelper.GetUCenterMemberRepository())
            {
                repository.DeleteRange(repository.Find(d => d.UserId == (Guid)e.User.ProviderUserKey));
                repository.Save();
            }
        }
        #endregion DeletedUser

        #endregion Event handlers

        #region Helpers
        private static void SetUcMember(int ucUid, Guid userId)
        {
            using (var repository = RepositroyHelper.GetUCenterMemberRepository())
            {
                var ucMember = repository.Get(userId) ?? new UCenterMember
                {
                    UserId = userId
                };
                ucMember.UcUId = ucUid;
                repository.Update(ucMember);
                repository.Save();
            }
        }
        #endregion Helpers
    }
}